<template>
  <el-dialog class="rulechain-validate-panel" :visible="visible" :modal="false" append-to-body @close="close">
    <div slot="title" style="font-weight: bold">车型匹配</div>
    <el-scrollbar class="content" :class="{collapse: isCollapse}" ref="scrollBar">
      <div class="content-group selected-vehicle">
        <div class="title">
          <span>选定车型({{ selectedVehicles.length }})</span>
          <el-button @click="openCcu" style="float:right">CCU / IDC版本</el-button>
        </div>
        <div class="list-group">
          <el-tooltip effect="dark" content="当前产品中使用的信号和服务不支持该车型" placement="top" v-for="(item, index) in selectedVehicles" :key="index" :disabled='getMatched(item)'>
            <el-tag
              class="model_tag selected"
              :class="{warn: !getMatched(item)}"
              :closable="editEnable && !item.old"
              :disable-transitions="true"
              @close="deleteSelected(index)">
              {{item.oem + '/' + item.series + '/' + item.model}}
            </el-tag>
          </el-tooltip>
        </div>
      </div>
      <div class="content-group apply-vehicle">
        <div class="title">适用车型({{ total }})</div>
        <div class="list-group">
          <div class="group-item" v-for="(value, key) in vehicleTree" :key="key">
            <div class="item-title">{{ key }}</div>
            <div class="item-list">
              <el-tag
                v-for="(item, index) in value"
                :key="index"
                :class="`model_tag ${selectedVehicles.some(el => el.modelCode === item.modelCode)}`"
                :disable-transitions="true"
                @click="addSelected(item)">
                {{item.oem + '/' + item.series + '/' + item.model}}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </el-scrollbar>
    <!-- <div class="bar-panel" :class="{collapse: isCollapse}" @click="togglePanelHeight"></div> -->
    <el-dialog title="修改CCU / IDC版本" :visible.sync="ccuDialog" width="500px" :before-close="clsoeCcu" class="choose-ccu-dialog" append-to-body :close-on-click-modal="false">
        <el-form :model="ccuForm" ref="ccuForm">
          <div class="choose-ccu-item" v-for="(item, index) in ccuForm.ccuList" :key="item.seriesId">
            <div class="title">{{ item.oem + '/' + item.series }}</div>
            <el-row>
              <el-col :span="8">
                <el-form-item label="CCU版本" :prop="'ccuList.' + index + '.ccu'" :rules="ccuRule">
                  <el-input v-model="item.ccu" type="text" name="searchText">
                    <template slot="prepend">S.</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="4">
                <el-form-item label="IDC版本" :prop="'ccuList.' + index + '.idc'" :rules="ccuRule">
                  <el-input v-model="item.idc" type="text" name="searchText">
                    <template slot="prepend">S.</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="clsoeCcu">取 消</el-button>
        <el-button type="primary" @click="submitCcu">确 定</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { deepClone } from '@/utils/helper/jsUtil'
import { mapState } from 'vuex'
export default {
  data() {
    const validatCcuRule = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else {
        if (/^[A-Z0-9][0-9]{2}$/.test(value)) {
          callback()
        } else {
          callback(new Error('版本号不正确'))
        }
      }
    }
    return {
      isCollapse: true,
      vehicleTree: {},
      ccuDialog: false,
      ccuForm: {
        ccuList: []
      },
      ccuRule: [{ required: false, validator: validatCcuRule, trigger: 'blur' }],
      total: null
    }
  },
  props: {
    visible: {
      type: Boolean
    },
    supportVehicles: {
      required: true,
      default: []
    }
  },
  computed: {
    ...mapState({
      productInfo: state => state.product.productInfo,
      editEnable: state => true
    }),
    defaultOemList() {
      return this.productInfo.defaultOemList || []
    },
    selectedVehicles() {
      this.productInfo.oemList?.forEach(item => { this.defaultOemList.some(oemItem => oemItem.modelCode === item.modelCode) && (item.old = true) }) // 老车型不可删除
      return this.productInfo.oemList || []
    }
  },
  watch: {
    supportVehicles: {
      handler(val) {
        this.generatorVehicleModelTree(val)
        this.total = val.length
      },
      immediate: true
    }
  },
  methods: {
    getMatched(item) {
      const itemId = item.modelCode
      const matched = this.supportVehicles.find(el => el.modelCode === itemId)
      return !!matched
    },
    generatorVehicleModelTree(originData) {
      const res = {}
      originData.forEach(el => {
        const itemKey = `${el.oem}/${el.series}`
        if (!Object.hasOwnProperty.call(res, itemKey)) {
          res[itemKey] = []
        }
        res[itemKey].push(el)
      })
      this.vehicleTree = res
    },

    deleteSelected(index) {
      const selectedVehicles = deepClone(this.selectedVehicles)
      selectedVehicles.splice(index, 1)
      this.$store.dispatch('product/updateProductVehicles', selectedVehicles)
    },

    addSelected(item) {
      if (this.editEnable) {
        if (!this.selectedVehicles.find(el => el.modelCode === item.modelCode)) {
          const selectedVehicles = deepClone(this.selectedVehicles)
          selectedVehicles.push(item)
          this.$store.dispatch('product/updateProductVehicles', selectedVehicles)
        }
      }
    },
    openCcu() {
      this.ccuDialog = true
      // 初始化列表
      const newCcuList = []
      this.selectedVehicles.filter((item, index) => {
        return (this.selectedVehicles.findIndex(sub => sub.seriesCode === item.seriesCode) === index)
      }).forEach(item => {
        const oldItem = deepClone(this.productInfo.ccuIdcVersionList.find(old => old.seriesCode === item.seriesCode))
        if (oldItem) {
          oldItem.series = item.series
          oldItem.oem = item.oem
          oldItem.ccu = oldItem.ccu ? oldItem.ccu.slice(2) : oldItem.ccu
          oldItem.idc = oldItem.idc ? oldItem.idc.slice(2) : oldItem.idc
          newCcuList.push(oldItem)
        } else {
          newCcuList.push({
            seriesCode: item.seriesCode,
            series: item.series,
            oem: item.oem,
            ccu: '',
            idc: ''
          })
        }
      })
      this.ccuForm.ccuList = newCcuList
    },
    clsoeCcu() {
      this.ccuDialog = false
      this.$refs.ccuForm.clearValidate()
    },
    submitCcu() {
      this.$refs.ccuForm.validate(valid => {
        if (valid) {
          this.clsoeCcu()
          setTimeout(() => {
            this.ccuForm.ccuList.forEach(item => {
              item.ccu = item.ccu ? 'S.' + item.ccu : ''
              item.idc = item.idc ? 'S.' + item.idc : ''
            })
            this.$store.dispatch('product/updateCCUList', this.ccuForm.ccuList)
          }, 500)
        }
      })
    },
    togglePanelHeight() {
      this.isCollapse = !this.isCollapse
      this.$nextTick(() => {
        this.$refs.scrollBar.update()
      })
    },
    close() {
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style lang="scss">
.rulechain-validate-panel {
  .el-dialog {
    position: absolute;
    top: 16px;
    left: 16px;
    right: 16px;
    width: auto;
    transform: none;
  }
  .el-dialog__body {
    padding: 0 24px 24px;
    overflow: hidden;
  }
  .title {
    font-size: 14px;
    font-weight: bold;
    margin: 20px 0;
  }
  .list-group{
    padding-bottom: 10px;
    border-bottom: 1px solid #ebebeb;
    min-height: 43px;
  }
  .content {
    height: 60vh;
    overflow: hidden;
    &.collapse {
      height: 38vh;
    }
    .content-group {
      overflow: hidden;
    }
    .list-group {
      border-bottom: 1px solid #ccc;
      &:last-child {
        border: none;
      }
      .group-item {
        margin-bottom: 20px;
        .item-title {
          font-size: 14px;
          color: #a3a3a3;
          margin-bottom: 16px;
        }
      }
    }
    .el-scrollbar__wrap {
      overflow: auto;
    }
  }
  .model_tag {
    margin: 0 8px 8px 0;
    cursor: pointer;
    color: #1f1f1f;
    background-color: #fff;
    border: 1px solid #DDD;
    &.selected {
      color: #486cff;
      border: 1px solid #edf0ff;
      cursor: default;
      background: #edf0ff;
      .el-tag__close {
        cursor: pointer;
        color: #486cff;
        font-size: 16px;
      }
      &:hover {
        border: 1px solid #edf0ff;
      }
    }
    &:hover {
      border: 1px solid #bbb;
    }
    &.true {
      cursor: default;
      color: #a3a3a3;
      border: 1px solid #F5F5F5;
      background: #F5F5F5;
    }
    &.warn {
      color: #e6534e;
      background: #fff0f0;
      border: 1px solid #fff0f0;
      .el-tag__close {
        color: #e6534e;
      }
    }
    .el-tag__close:hover {
      background: #ccc;
    }
  }
  .bar-panel {
    display: block;
    position: absolute;
    left: 50%;
    bottom: 0;
    width: 98px;
    height: 12px;
    background: url("../../assets/bottom_drawer_close.png") center center no-repeat;
    transform: translateX(-50%);
    cursor: pointer;
    z-index: 100;
    &.collapse {
      background: url("../../assets/bottom_drawer_open.png") center center no-repeat;
    }
  }
}
.rulechain-validate-panel.el-dialog__wrapper {
  left: 296px;
  top: 60px;
}
.choose-ccu-dialog{
  .el-dialog__body{
    padding: 16px 16px 0;
  }
  .choose-ccu-item{
    background-color: #F2F3F5;
    margin-bottom: 16px;
    padding: 10px;
    .el-form-item__error{
      margin-left: 54px;
    }
  }
}
</style>
